/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {DeviceEventEmitter, Image, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import RegisterIBMThreePage from "../../common/register/RegisterIBMThreePage";
import BasicInfoPage from "./BasicInfoPage";
import AlertDialog from "../../../custom/AlertDialog";
import PlansMainPage from "./PlansMainPage";
import SubAccountsPage from "./SubAccountsPage";
import VerifyPersonalPage from "./VerifyPersonalPage";


export default class BusinessPlanPage extends Component {
    constructor(props) {
        super(props);
        this.usersData = [];
        this.planNames = [
            {
                name: I18n.t('b.rocketProgramContent'),
                rank: 2,
            },
            {
                name: I18n.t('b.goodToGoContent'),
                rank: 3,
            },
            {
                name: I18n.t('b.growTogetherContent'),
                rank: 4,
            },
            {
                name: I18n.t('b.matrixContent'),
                rank: 5,
            },
            {
                name: I18n.t('b.u_2Program'),
                rank: 6,
            },
            {
                name: I18n.t('b.plan7'),
                rank: 7,
            },
            {
                name: I18n.t('b.plan8'),
                rank: 8,
            },
        ];

        this.state = {
            alertVisible: false,
            rankData: null,
            alertContentTxt: I18n.t('default.notAvailabelInYourCountry'),

            isActivatedPlans: [],
            isNotActivatedPlans: [],

        };
        this.iparNetwork = new IparNetwork();
        this.country_iso = '';
    }


    componentWillUnmount() {
        this.iparNetwork = null;
        this.planNames = null;
        this.country_iso = null;
    }

    componentDidMount() {
        CommonUtils.showLoading();

        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                CommonUtils.getAcyncInfo('country_iso')
                    .then((country_iso) => {
                        this.country_iso = country_iso;
                        this.userData = JSON.parse(result);
                        this.onLoadRenkData();
                    });
            });


    }


    /**
     * 获取奖励计划数据
     */
    onLoadRenkData() {
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getRank?', 'country=' + this.country_iso)
            .then((result) => {
                this.getUserInfo(result.data);
                if (result.code === 200) {
                    this.setState({
                        rankData: result.data,
                    })
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('BusinessPlanPage----onLoadRenkData--error-', error);
            })
    }


    /**
     *网络请求
     *
     * 获取用户详细信息
     */
    getUserInfo(rankDatas) {
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getSubAccount?', 'main_user_id=' + this.userData.main_user_id)
            .then((result) => {
                if (result.code === 200) {
                    let mainUerData = result.data[0];
                    this.usersData = result.data;

                    let openPlans = mainUerData.open_plan + '';
                    let _isActivatedPlans = [];
                    let _isNotActivatedPlans = [];
                    for (let i = 0, len = rankDatas.length; i < len; i++) {
                        let rankData = rankDatas[i];
                        if (openPlans.indexOf(rankData.rank) !== -1) {//用户已开通
                            _isActivatedPlans.push(rankData)
                        } else {//用户未开通
                            _isNotActivatedPlans.push(rankData)
                        }
                    }

                    this.setState({
                        isActivatedPlans: _isActivatedPlans,
                        isNotActivatedPlans: _isNotActivatedPlans,
                    });
                }
                CommonUtils.dismissLoading();

            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error)
            })
    }


    onPlanClick(planData) {


        let _component = null;
        let _params = {};
        let rank = planData.rank;

        let mainUserId = this.userData.main_user_id;
        if (this.userData.rank > 1 &&
            this.userData.is_contract === 1 &&
            this.userData.is_buy === 1) {
            _component = PlansMainPage;
            _params = {userId: mainUserId}
        } else if (rank === 2 || rank === 3 || rank === 4 || rank === 7) {
            let _userData = this.userData;
            for (let dataRow of this.usersData) {
                if (dataRow.rank == rank) {
                    _userData = dataRow;
                    break;
                }
            }
            _component = BasicInfoPage;
            _params = {
                title: planData.rank_name,
                userData: _userData,
            }
        } else if (rank === 5 || rank === 6 || rank === 8) {
            _component = SubAccountsPage;
            _params = {
                userId: mainUserId,
                rank: rank,
            };
        }

        if (_component) {
            this.props.navigator.push({
                component: _component,
                name: _component + '',
                params: _params,
            })
        }

    }

    render() {


        let state = this.state;


        return (
            <View style={[StyleUtils.flex, {backgroundColor: 'white'}]}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />
                <ScrollView style={StyleUtils.flex}>
                    <View style={{paddingLeft: 16, paddingRight: 16}}>
                        {ViewUtils.getTitleView(I18n.t('default.businessPlan'), I18n.t('default.iparProvidesYou'))}
                        <View style={StyleUtils.lineStyle}/>

                        {state.isNotActivatedPlans.length > 0 ?
                            <View>
                                <Text
                                    style={[styles.successTv, StyleUtils.smallFont]}>{I18n.t('default.notActivated')}</Text>
                                {state.isNotActivatedPlans.map((item, i) => {
                                    let planLableText = this.planNames[item.rank - 2] ? this.planNames[item.rank - 2].name : '';
                                    return ViewUtils.gitUserInformationTv(item.rank_name, planLableText, require('../../../res/images/ic_selected.png'),
                                        () => {
                                            this.props.navigator.push({
                                                component: RegisterIBMThreePage,
                                                name: 'RegisterIBMThreePage',
                                                params: {
                                                    selectPlan: item
                                                }
                                            })
                                        })
                                })}
                            </View>
                            : null}

                        {state.isActivatedPlans.length > 0 ?
                            <View>
                                <Text
                                    style={[styles.successTv, StyleUtils.smallFont]}>{I18n.t('default.activated')}</Text>
                                {state.isActivatedPlans.map((item, i) => {
                                    let planLableText = this.planNames[item.rank - 2] ? this.planNames[item.rank - 2].name : '';
                                    return ViewUtils.gitUserInformationTv(item.rank_name, planLableText, require('../../../res/images/ic_selected_in.png'),
                                        () => this.onPlanClick(item))
                                })}
                            </View>
                            : null}

                    </View>

                </ScrollView>

                <AlertDialog
                    centerSts={'ok'}
                    contentTv={state.alertContentTxt}
                    singleBtnOnclick={() => this.setState({alertVisible: false})}
                    visible={state.alertVisible} requestClose={() => {
                    this.setState({alertVisible: false})
                }}/>
            </View>
        );
    }


}

const styles = StyleSheet.create({

    successTv: {
        fontSize: 25,
        color: 'black',
        marginTop: 16,
        marginBottom: 16,
        textAlign: 'left'
    },
    progressBar: {
        borderWidth: Platform.OS === 'ios' ? 1 : 0.7,
        borderColor: '#cccccc',
        width: '100%',
        flex: 1,
    },
    progressTv: {
        width: 50,
        fontSize: 17,
        marginLeft: 5,
        height: 22,
        lineHeight: 22
    },
    progressBox: {
        width: '100%',
        height: 80,
        flexDirection: 'column',
        backgroundColor: '#f9f9f9',
        marginTop: 30,
        paddingLeft: 10
    },
    notActiTv: {
        textAlign: 'center',
        marginTop: 16,
        color: 'gray',
        fontSize: 15
    }

});
